import { Component, OnInit } from '@angular/core';
import {Rule} from "../rule";
import {Router, ActivatedRoute} from "@angular/router";
import {RuleService} from "../rule.service";
import {ResponseUtil} from "../../../../../util/response-util";
import {MsgResult} from "../../../../../models/msg-result";
import {Path} from "../../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../../util/page-subject";
import {OneDialogService} from "../../../../../widgets/one-dialog/one-dialog.service";
import {MsgConstants} from "../../../../../constants/constants";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
@Component({
  selector: 'app-rule-update',
  templateUrl: './rule-update.component.html',
  styleUrls: ['./rule-update.component.css']
})
export class RuleUpdateComponent implements OnInit {

  //声明实例
  rules :Rule;

  rulesForm : FormGroup;

  constructor(
    private router : Router,
    private route : ActivatedRoute,
    private pageSubject : PageSubject,
    private ruleService : RuleService,
    private dialogService : OneDialogService,
    private responseUtil : ResponseUtil,
    private fb: FormBuilder,
  ) {
    this.initObject();
  }


  ngOnInit() {
    //初始化表单
    this.initUpdateFrom();
    this.pushPage();
  }

  /**
   * 面包屑导航
   */
  pushPage(){
    let path = new Path("报警管理","");
    this.pageSubject.pushPage("规则管理","修改",path);

  }

  //修改规则信息
  onSubmit(){
    this.ruleService.updateRule(this.rulesForm.value).subscribe(
      result=>this.responseUtil.success(result,this.processUpdateResult),
      message =>this.responseUtil.error(message)
    );
  }

  /**
   * 修改成功后调用
   * @param json
   */
  private processUpdateResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message, () => this.cancelRuleUpdate());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  //取消修改资源
  cancelRuleUpdate(){
    this.router.navigate(['..'],{relativeTo : this.route});
  }

  /**
   * 实例化对象
   */
  private initObject(){
    this.rules =new Rule("","","","","0");
    this.buildForm();
  }

  /**
   * 构造表单
   */
  buildForm(): void {
    this.rulesForm = this.fb.group({
      'id': [this.rules.id ],
      'ruleName': [this.rules.ruleName,[
        Validators.required
      ]],
      'operation': [this.rules.operation],
      'value': [this.rules.value],
      'isUse': [this.rules.isUse],
    });

    this.rulesForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }

  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.rulesForm) {
      return;
    }
    const form = this.rulesForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'ruleName': ''
  };
  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'ruleName': {
      'required': '名称不能为空'
    }
  };

  /**
   * 通过id查询
   */
  initUpdateFrom() {
    //获取路由参数
    let id = this.route.snapshot.params["id"];
    this.ruleService.getRuleById(id).subscribe(
      result => this.responseUtil.success(result, this.processGetResult),
      error => this.responseUtil.error(error)
    );
  }
  /**
   * id查询成功后调用
   * @param json
   */
  private processGetResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.rules = result.data;
      this.rulesForm.patchValue(this.rules);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

}
